import Vue from 'vue'
import Router from 'vue-router'
import Login from './views/Login.vue'
import Home from './views/Home.vue'

Vue.use(Router)

const router =  new Router({
  routes: [
    {
      path: '/',
      name: 'login',
      component: Login,
      meta: {
        requireAuth: false
      }
    },
    {
      path: '/home',
      name: 'home',
      // route level code-splitting
      // this generates a separate chunk (about.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: Home,
      meta: {
        requireAuth: false
      },
      children: [
        {
          path: '/dashboard',
          name: 'dashboard',
          component: () => import('./views/Dashboard.vue'),
          meta: {
            requireAuth: false // 添加该字段，表示进入这个路由是需要登录的
          }
        },
        {
          path: '/sys/menu',
          name: 'menu',
          component: () => import('./views/sys/Menu.vue'),
          meta: {
            requireAuth: false
          }
        },
        {
          path: '/sys/user',
          name: 'user',
          component: () => import('./views/sys/User.vue'),
          meta: {
            requireAuth: false
          }
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  console.log(to.meta.requireAuth)
  if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
    if (store.state.token) { // 通过vuex state获取当前的token是否存在
      next()
    } else {
      next({
        path: '/'
        // query: {redirect: to.fullPath} // 将跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  } else {
    next()
  }
})

export default router

